import { getHomeRoute, localSave, localRead } from '@/libs/util'
import config from '@/config'
const { homeName } = config

export default {
	state: {
		homeRoute: {},
		local: 'zh-CN',
		pageCacheList: [],
		system: {
			isGetData: false,
			Lang: 'zh-CN',
			AutoUpgradeEnabled: 1,
			AutoStartEnabled: 1,
			VoiceWakeUpEnabled: 1,
			AppShortcutKey: 'win+?',
			ConflictReminderEnabled: 1,
			AutoVoicePlay: 1,
			VoiceWakeUpPrompt: '你好小蟹',
			version: '1.0.0'
		},
		newVersion: localRead('newVersion')
	},
	mutations: {
		setSystem(state, system) {
			state.system = system
		},
		setHomeRoute(state, routes) {
			state.homeRoute = getHomeRoute(routes, homeName)
		},
		setLocal(state, lang) {
			state.system.Lang = lang
			state.local = lang
		},
		setNewVersion(state, version) {
			localSave('newVersion', version)
			state.newVersion = version
		},
		ADDPageCache(state, pageName) {
			state.pageCacheList.push(pageName)
		},
		DELPageCache(state, pageName) {
			state.pageCacheList.forEach((page, index) => {
				if (page === pageName) {
					state.pageCacheList.splice(index)
				}
			})
		}
	},
	getters: {
		permissions: (state) => state.authFuncList,
		getPageCacheList: (state) => {
			return state.pageCacheList
		},
		system: (state) => {
			return state.system
		},
		local: (state) => {
			return state.system.Lang
		}
	},
	actions: {
		add({ commit }, pageName) {
			commit('ADDPageCache', pageName)
		},
		delete({ commit }, pageName) {
			commit('DELPageCache', pageName)
		},
		async getSystem({ commit, state }) {
			if (!state.system.isGetData) {
				let model = {}
				const res = await chrome.webview.hostObjects.form.GetConfigAsync()
				let value = JSON.parse(res)
				console.log(value)
				value.forEach((item) => {
					if (!isNaN(item.Value)) {
						model[item.Key] = parseFloat(item.Value)
					} else {
						model[item.Key] = item.Value
					}
				})
				model.isGetData = true
				console.log(model)
				model = { ...state.system, ...model }
				console.log(model)
				commit('setSystem', model)
			}
		}
	}
}
